//
//  EditViewController.swift
//  CJXSwiftStoryboard
//
//  Created by CJX on 2016/11/15.
//  Copyright © 2016年 caijianxi. All rights reserved.
//

import UIKit
import SwiftyJSON
import SVProgressHUD

class EditViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    
    var productID : String?
    
    var myTableView = UITableView(frame: CGRect(x: 0, y: 64, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-64), style: .grouped)
    
    let EDITTABLEVIEWCELL = "EditTableViewCell"
    
    var starView : XHStarView?
    
    var editText : String?
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()


        self.creatNavBtn()
        self.creatView()
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension EditViewController{
    fileprivate func creatNavBtn(){
        
        self.title = "Write An Review"
        self.automaticallyAdjustsScrollViewInsets = false
        
        let leftBtn = UIButton(type: .custom)
        leftBtn.setImage(UIImage(named: "nav_back"), for: UIControlState())
        leftBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        leftBtn.addTarget(self, action: #selector(leftBtnClick), for: .touchUpInside)
        let item = UIBarButtonItem(customView: leftBtn)
        self.navigationItem.leftBarButtonItem = item
        

        
        
        let rightItemCustomeView   = UIButton(type: UIButtonType.custom);
        rightItemCustomeView.frame = CGRect(x: 0, y: 0, width: 30, height: 30);
        rightItemCustomeView.setImage(UIImage(named:"nav_close"), for: UIControlState())
        rightItemCustomeView.addTarget(self, action: #selector(rightButtonClick), for: UIControlEvents.touchUpInside)
        let colseBarButtonItem = UIBarButtonItem(customView: rightItemCustomeView)
        
        
        self.navigationItem.rightBarButtonItems = [colseBarButtonItem];
        
        
    }
    
    
    
    func leftBtnClick(){
        self.navigationController?.popViewController(animated: true)
    }
    

    func rightButtonClick()
    {
        
        self.navigationController?.popToRootViewController(animated: true);
    }
    
    
}

extension EditViewController{
    
    fileprivate func creatView(){
        
        
        
        myTableView.delegate = self
        myTableView.dataSource = self
        self.view.addSubview(myTableView)
        
        let nib = UINib(nibName: "EditTableViewCell", bundle: nil)
        myTableView.register(nib, forCellReuseIdentifier: EDITTABLEVIEWCELL)
        
        
        
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: EDITTABLEVIEWCELL) as! EditTableViewCell
        
        editText = cell.edittextView.text
        cell.submitBtn.addTarget(self, action: #selector(submitBtnClick), for: .touchUpInside)
        
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headView = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT*0.15))
        headView.backgroundColor = UIColor.white
        
        let label = UILabel(frame: CGRect(x: 20, y: 3, width: SCREEN_WIDTH-20, height: SCREEN_HEIGHT*0.15*0.4-6))
        label.text = "RATEING"
        headView.addSubview(label)
        
        starView = XHStarView.load()
        starView?.frame = CGRect(x: 20, y: SCREEN_HEIGHT*0.15*0.4+5, width: SCREEN_WIDTH-40, height: SCREEN_HEIGHT*0.15*0.6-10)
        headView.addSubview(starView!)
        
        
        
        return headView
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return SCREEN_HEIGHT*0.15
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return SCREEN_HEIGHT * 0.6
    }
    
    
    func submitBtnClick(){
        let cell = myTableView.cellForRow(at: NSIndexPath(row: 0, section: 0) as IndexPath) as! EditTableViewCell
        
        
        let urlStr = APIBASE + "main_page=product_reviews_write"
//        let number = Float((self.starView?.score2)!)
        let number = Float(5)
        let numStr = String(describing: self.starView?.score2)
        
        let num = number as NSNumber
        
        let editStr = cell.edittextView.text
        print(String(describing: editStr!))
        print(self.productID!)
        print(self.starView?.score2)
        print(num)
        let parma = ["products_id":self.productID!,"review_text":editStr!,"rating":num] as [String : Any]
        
        NetworkTool.shareInstance.request(.post, urlString: urlStr, parmas: parma as! [String : NSObject]){ (result, error) in
            
            if result != nil{
                let json = JSON(result!)
                print(json)

                let status = Int(((result as? NSDictionary)!["status"]as?NSNumber)!)
                if status == 1{
                    
                    SVProgressHUD.showSuccess(withStatus: "Successfully!")
                    
                }else{
                    SVProgressHUD.showInfo(withStatus: "Review status:"+String(describing: (result as? NSDictionary)!["status_message"]!))
                    print("Review status:"+String(describing: (result as? NSDictionary)!["status_message"]!))
                }
        
            }else{
                SVProgressHUD.show(withStatus: "Review error:"+String(describing: error))
                print("Review error:"+String(describing: error))
            }

        }
    }
    
}












